<?php
/**
* Multi purpse image contents server
* @todo if the images are served slowly, it will not render the images back to the browser for the first time.
*/

# Potential hotlinking URLs to the images:
# image/1/2/3.jpg album/size/image
# image/2/3.jpg size/image
# image/3.jpg image
# 3.jpg image

$album_id = $variable->get('album_id', 'integer', 0);
$size_id = $variable->get('size_id', 'integer', DEFAULT_SIZE_ID);
$image_id = $variable->get('image_id', 'integer', 0);

# Prohibit downloading original image file
# We will have some alternative way.
if($size_id == THUMBNAIL_ORIGINAL_SIZE_ID) die('Download obstructed at the moment.');

# if image valid
if(!$image_id) die("What are you searching for?");

$images = new images();

if($is_admin = $variable->session('is_admin', 'boolean', false))
{
	#die('I will skip testing valid images for admins.');
}
else
{
	# All other users must ensure that they are accessing valid iamges only
	if(!$images->is_valid_image($image_id)) die("Image invalid (or not yet released) for non-admin users.");
	
	# But when the image request is for album cover image, so some valid image
	# ...
}

# validate from db if we can show this image

# if not album id, find it via image id
# Also, checks if the image is valid.
if(!$album_id)
{
	$album_id = $images->album_id($image_id);
	
	# We must have the album records as well.
	if(!$album_id) die("Invalid image request.");
}
#die("Album/Size/Image = {$album_id}/{$size_id}/{$image_id}");

# Find if the album is valid

# find if size is valid

# Find album size location
$albumsizes = new albumsizes();
$store_location = $albumsizes->store_location($album_id, $size_id);
#die("Album size expectedly stored at: {$store_location}");

# MS Windows characters: :, \
#$store_location = preg_replace('/[^a-z0-9\ \-\_\:\\\]/is', '', $store_location);
#$store_location = str_replace(array('\t', '\r', '\n'), array('', '', ''), $store_location);
if(!$store_location) die('Store location does not exist.');
if($store_location=='/tmp') die("This album #{$album_id} does not have size #{$size_id}.");
if(!is_dir($store_location))
{
	# Try to make it for the first time users.
	/**
	* @todo Verify that thte calls are ok, and prevent making a lot of (unwanted) directories.
	*/
	if(!mkdir($store_location, 0777, true))
	{
		die("Cannot create store location {$store_location}");
	}
}

# if location is not found, error

# if image size does not exist, error
$thumbnail_file = "{$store_location}/{$image_id}.jpg";
#die("Will serve image file - {$thumbnail_file}, Size ID: #{$size_id}");
#if(!is_file($thumbnail_file)) die('Image file not found.');
# Rather, try to create the image thumb there.
# Commenting the line below will create thumbmails everything. Be careful.
if(!is_file($thumbnail_file))
{
	# Below scripts run only once
	# It can become a CPU intensive task
	
	$sizes = new sizes();
	$size_details = $sizes->details($size_id);
	if(!$size_details) die("Missing size details.");
	#print_r($size_details); die();
	#die("Requested image size: {$size_details['dimension_width']}x{$size_details['dimension_height']}");
	
	# Find out the original reference to the image at the time of scanning it.
	
	$originally_scanned_size_id=THUMBNAIL_ORIGINAL_SIZE_ID;
	
	# Find out the store of orignal images of this album
	$store_location_originally_scanned = $albumsizes->store_location($album_id, $originally_scanned_size_id);
	if(!is_dir($store_location_originally_scanned)) die("Original image not existing.");
	#die("Original image scanned from: {$store_location_originally_scanned}");
	
	# Find out the base name of the image
	$base_name_original = $images->base_name($image_id);
	if(!$base_name_original) die("Missing base/original image #{$image_id}");
	#die("Base name: {$base_name_original}");
	
	# Full path to the orignal image should exist
	$original_image_name_path = "$store_location_originally_scanned/{$base_name_original}";
	if(!is_file($original_image_name_path)) die("Original image missing: {$original_image_name_path}");
	#die("Original file: {$original_image_name_path}");
	
	# Find out the too-customized image size details | optional
	$image_size_details = $sizes->image_size($image_id, $size_id);
	if(!$image_size_details)
	{
		$image_size_details = array(
			'cropnail_x' => 0,
			'cropnail_y' => 0,
		);
	}
	$cropnail_xy = '';
	if($size_details['do_logomark']=='Y')
	{
		# Save the logo marked image
		$logomark = new logomark(__BASE__.'/'.LOGOMARK_IMAGE_FULLPATH);
		if($image_size_details) $logomark->set_xy($image_size_details['cropnail_x'], $image_size_details['cropnail_y']); # For cropnail only | optional
		$logomark->resize_to($size_details['dimension_width'], $size_details['dimension_height']);
		$logomark->save_to($thumbnail_file);
		$logomark->show_image($original_image_name_path);
	}
	else
	{
		# Just resize and save it (without the logo mark)
		$cropnail = new cropnail($size_details['dimension_width'], $size_details['dimension_height']);
		if($image_size_details) $cropnail->set_xy($image_size_details['cropnail_x'], $image_size_details['cropnail_y']); # For cropnail only | optional
		$cropnail->resize($original_image_name_path, $thumbnail_file);
		$cropnail_xy = $cropnail->x1y1x2y2();
	}
	
	# Save the cropnail (x1,y1), (x2,y2)
	# (x1,y1): $image_size_details['cropnail_x'], $image_size_details['cropnail_y']
	$x = (int)$image_size_details['cropnail_x'];
	$y = (int)$image_size_details['cropnail_y'];
	$gallery_images_sizes_sql="
INSERT INTO gallery_images_sizes (
	image_id, size_id,
	cropnail_x, cropnail_y, cropnail_xy,
	subdomain_id, added_on, is_active, is_approved
) VALUES (
	{$image_id}, {$size_id},
	{$x}, {$y}, '{$cropnail_xy}',
	{$subdomain_id}, UNIX_TIMESTAMP(CURRENT_TIMESTAMP()), 'Y', 'Y'
) ON DUPLICATE KEY UPDATE
	cropnail_x={$x},
	cropnail_y={$y},
	cropnail_xy='{$cropnail_xy}',
	modified_ON=UNIX_TIMESTAMP(CURRENT_TIMESTAMP()),
	modified_counter=modified_counter+1
;";
	$images->query($gallery_images_sizes_sql);
}

# Show the image
if(!is_file($thumbnail_file))
{
	#die("Thumbnail file is mising - I cannot make/show it now. {$thumbnail_file}");
	$thumbnail_file = __BASE__.'/templates/images/image-missing.jpg';
}

# Ahh, finally
headers::cache(); headers::image('jpg'); readfile($thumbnail_file);
#die("Everything successful.");
?>